#include "timerLedCube.h"
#include <reg51f.h>
extern int timeOut;
unsigned char led7_data[10] = {0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
unsigned char led7_buffer[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
unsigned int position = 0;
unsigned char led7_index = 0;
unsigned char is_valid_data = 0;
extern unsigned char datatoLed[8];
extern unsigned char dataLed[8] ;
  void Init_Timer0()	//used for timeout
{
	TMOD |= 0x01;
	ET0 = 1;
	TF0 = 1;

}
void Start_Timer0(){
 	TH0 = (-10000)/256;
	TL0 = (-10000)%256;
	TR0 = 1;
}
void Stop_Timer0(){
 	TR0=0;
} 
 void Timer0 (void) interrupt 1	 {
	TR0 = 0;
	TH0 = (-10000)/256;
	TL0 = (-10000)%256;
	TR0 = 1;
	timeOut++;
}
void Init_Timer1() //use for display {
	TMOD |= 0x10;
	ET1 = 1;
	TF1 = 1;
	TR1 = 1 ;
	TH1 = 0xff;	//setup counter 
	TL1 = 0x00;	// 
}
void init_led7(){
	P0 = 0xff; //data port
	P1 = 0xff; //selected port
	position = 0; //output index
	led7_index = 0; //scan index
	is_valid_data = 1;
}

void clear_led7() {
	led7_buffer[0] = 0x00;
	led7_buffer[1] = 0x00;
	led7_buffer[2] = 0x00;
	led7_buffer[3] = 0x00;

	led7_buffer[4] = 0x00;
	led7_buffer[5] = 0x00;
	led7_buffer[6] = 0x00;
	led7_buffer[7] = 0x00;
}
void store_led7(){	int i;
 	is_valid_data = 0;
	
		for(i=0;i<8;i++){
			led7_buffer[i]=led7_data[dataLed[i]];
		}
	is_valid_data = 1;
}  
void set_position(unsigned int pos) //set position to begin output
{
	position = pos;
}

unsigned int get_position() //get current position
{
	return position;
}

void scan_led7()
{
	if(is_valid_data)
	{
		P1 = 0x00;
		P0 = led7_buffer[led7_index];
		P1 = 1 << led7_index;
		led7_index++;
		if(led7_index == 8)
			led7_index = 0;	
	}
}


void StopTimer1(){
	TR1	= 0;
}
void StartTimer1(){
	TR1 = 1;	
}
void timer1_isr()interrupt 3{
	if(is_valid_data==1){	
//	TR1 = 0;	//stop timer 1
//	TF1 = 0; 	//erase timer 1 flag
	
	TH1 = 0xff;// reinitialize 
	TL1 = 0x00;		
	scan_led7();
//	TR1 = 1;	//start timer 1
	}
}
/*
void Init_Timer0()	//used for timeout
{
	TMOD |= 0x01;
	ET0 = 1;
	TF0 = 1;
}	
	
void Int_Enable()
{
	EA = 1;
}	  
void Timer0 (void) interrupt 1
{
	TR0 = 0;
	TH0 = (-2500/256);
	TL0 = (-2500%256);
	Dongchot;

}
void Timer1 (void) interrupt 3
{
	TR1 = 0;
	TH1 = (-2500/256);
	TL1 = (-2500%256);			
	display();
/*	if(counter1++ == 500){
		counter1= 0;
//		UpdateRedBuffer(send_buff[displayNumber++]);
		if(displayNumber >= index)
			displayNumber = 0;
	}  

	TR1 = 1;
}
void stopTimer0(){
	TR0 = 0;
}
void startTimer0(){
	TR0 = 1;
}
void countTimer0(unsigned int counter){
	 counter0 = counter;
}							 */